package ua.senfiron.vk.photo.viewer;

import java.util.ArrayList;

import ua.senfiron.vk.photo.viewer.ConnectivityChangeReceiver.ConnectivityChangeListener;
import ua.senfiron.vk.photo.viewer.util.GridViewUtilities;
import ua.senfiron.vk.photo.viewer.util.NetworkUtilities;
import ua.senfiron.vk.photo.viewer.vkprovider.VkPhoto;
import ua.senfiron.vk.photo.viewer.vkprovider.VkProvider;
import ua.senfiron.vk.photo.viewer.vkprovider.VkProvider.OnPhotosLoadedListener;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.NavUtils;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.ProgressBar;

public class PhotoListActivity extends ActionBarActivity {

    private int mImageThumbSize;
    private int mImageThumbSpacing;
    private ProgressBar mProgressBar;
    private GridView mGridView;
    private VkProvider mVkProvider;
    private VkPhotoAdapterAbstract<VkPhoto> mAdapter;
    private boolean mShouldDisplayPhotoTitle = true;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.image_grid);
        // Show the Up button in the action bar.
        setupActionBar();
        mVkProvider = VkProvider.getInstance();
        mProgressBar = (ProgressBar) findViewById(R.id.progressBarImageGrid);
        mGridView = (GridView) findViewById(R.id.gridViewImageGrid);
        
        if(mVkProvider.getCurrentAlbum().getPhotos().isEmpty()) {
            refresh();
        } else {
            mProgressBar.setVisibility(View.GONE);
            mGridView.setVisibility(View.VISIBLE);
        }
        
        mAdapter = new VkPhotoAdapterAbstract<VkPhoto>(mVkProvider.getCurrentAlbum().getPhotos()) {
            
           @Override
            public String getItemText(int position) {
               if(!mShouldDisplayPhotoTitle)
                   return null;
               return mArray.get(position).getText();
            }
            
            @Override
            public String getItemImageUrl(int position, int itemHeight) {
                return mArray.get(position).getOptimalThumbSrc(itemHeight);
            }
        };
        
        mGridView.setAdapter(mAdapter);
        
        mImageThumbSize = getResources().getDimensionPixelSize(R.dimen.image_thumbnail_size);
        mImageThumbSpacing = getResources().getDimensionPixelSize(R.dimen.image_thumbnail_spacing);

        mGridView.getViewTreeObserver().addOnGlobalLayoutListener(
                new ViewTreeObserver.OnGlobalLayoutListener() {
                    @Override
                    public void onGlobalLayout() {
                        GridViewUtilities.gridViewUpdateCellSize(mGridView, mAdapter, mImageThumbSize, mImageThumbSpacing);
                    }
                });
        mGridView.setOnItemClickListener(
                new OnItemClickListener() {

                    @Override
                    public void onItemClick(AdapterView<?> parent, View v, int position, long id) {

                        mVkProvider.setCurrentPhotoIndex((int) id);
                        goForward();
                    }
                });
        PhotoListActivity.this.setTitle(mVkProvider.getCurrentAlbum().getTitle());
    }
    
    @Override
    protected void onStart() {
        super.onStart();
        SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);
        boolean previousValue = mShouldDisplayPhotoTitle;
        mShouldDisplayPhotoTitle = pref.getBoolean("display_photo_title", false);
        if(mShouldDisplayPhotoTitle != previousValue) {
            mAdapter.notifyDataSetChanged();
        }
    }
    
    private void refresh() {
        
        if(!ConnectivityChangeReceiver.isNetworkConnected(this)) {
            NetworkUtilities.showInternetNotAvaliableDialog(this);
            ConnectivityChangeReceiver.setListener(new ConnectivityChangeListener() {
                
                @Override
                public void onNetworkConnected() {
                    refresh();
                }
            });
        }
        
        mGridView.setVisibility(View.GONE);
        mProgressBar.setVisibility(View.VISIBLE);
       
        mVkProvider.loadPhotosAsync(new OnPhotosLoadedListener() {

            @Override
            public void onPhotosLoaded(ArrayList<VkPhoto> photos) {
                
                if(mAdapter != null)
                {
                    mAdapter.notifyDataSetChanged();
                }
                mProgressBar.setVisibility(View.GONE);
                mGridView.setVisibility(View.VISIBLE);
                
            }
        });
    }

    private void goForward() {
        if(mVkProvider.getCurrentPhoto() != null) {
            Intent intent = new Intent(PhotoListActivity.this, ViewPhotoActivity.class);
            startActivity(intent);
        }           
    }

    private void goBack() {
        Intent resultIntent = new Intent();
        setResult(Activity.RESULT_OK, resultIntent);
        this.finish();
    }

    private void logout() {
        mVkProvider.logOut(this);
        Intent intent = new Intent(PhotoListActivity.this, VkLoginActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); // Removes other Activities from stack
        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        startActivity(intent);
    }

    /**
     * Set up the {@link android.app.ActionBar}, if the API is available.
     */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    private void setupActionBar() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case android.R.id.home:
            // This ID represents the Home or Up button. In the case of this
            // activity, the Up button is shown. Use NavUtils to allow users
            // to navigate up one level in the application structure. For
            // more details, see the Navigation pattern on Android Design:
            //
            // http://developer.android.com/design/patterns/navigation.html#up-vs-back
            //
            NavUtils.navigateUpFromSameTask(this);
            return true;
            
        case R.id.action_settings:
            Intent intent = new Intent(this, SettingsActivity.class);
            startActivity(intent);
            return true;
           
        case R.id.action_refresh:
            refresh();
            return true;
            
        case R.id.action_forward:
            goForward();
            return true;
            
        case R.id.action_back:
            goBack();
            return true;
            
        case R.id.action_logout:
            logout();
            return true;

        }
        return super.onOptionsItemSelected(item);
    }
}
